package org.jtrace.geometry;

import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;

import org.jtrace.Hit;
import org.jtrace.Jay;
import org.jtrace.Material;
import org.jtrace.Materials;
import org.jtrace.NotHit;
import org.jtrace.examples.io.SimplePLYExample;
import org.jtrace.io.PlyReader;
import org.jtrace.primitives.ColorRGB;
import org.jtrace.primitives.Point3D;

public class OctreeMesh extends Mesh {
	private Octree octree;	
	
	public OctreeMesh(String plyPath, Material material) {
		super(material);
		
		center = new Point3D(0, 0, 0);
		min = new Point3D(Double.MAX_VALUE, Double.MAX_VALUE, Double.MAX_VALUE);
		max = new Point3D(Double.MIN_VALUE, Double.MIN_VALUE, Double.MIN_VALUE);
		
		loadMesh(plyPath);
	}
	
	private void loadMesh(String plyPath) {
		InputStream is = SimplePLYExample.class.getResourceAsStream(plyPath);
		
		try {
			List<Triangle> triangles = PlyReader.read(is, Materials.metallic(ColorRGB.RED));
			
			for(Triangle triangle : triangles) {
				this.triangles.add(triangle);
				
				updateBounds(triangle.getV1());
				updateBounds(triangle.getV2());
				updateBounds(triangle.getV3());					
			}			
			
			updateCenter();
			
			octree = new Octree(this, min, max, 200, 10);
			octree.build();
			
			//this.triangles.addAll(triangles);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public Hit hit(Jay jay) {		
		return octree.hit(jay);
	}
}
